package com.nineclock.document.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itzhanshen.sys.feign.SysUserFeign;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NCException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.CurrentUserHolder;
import com.nineclock.document.dto.*;
import com.nineclock.document.enums.DocumentPermissionEnum;
import com.nineclock.document.mapper.DocCollaborationsMapper;
import com.nineclock.document.mapper.DocFileMapper;
import com.nineclock.document.mapper.DocFolderMapper;
import com.nineclock.document.pojo.DocCollaborations;
import com.nineclock.document.pojo.DocFile;
import com.nineclock.document.pojo.DocFolder;
import com.nineclock.document.service.AppDocService;
import com.nineclock.dto.SysCompanyUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;

@Service
@Transactional
public class AppDocServiceImpl implements AppDocService {
    @Autowired
    DocFolderMapper docFolderMapper;
    @Autowired
    DocFileMapper docFileMapper;
    @Autowired
    SysUserFeign sysUserFeign;
    @Autowired
    DocCollaborationsMapper docCollaborationsMapper;
    @Override
    public DocumentDto findFolderAndFile(Long parentFoldId) {
        // 获取当前企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();

        Long companyUserId = CurrentUserHolder.get().getCompanyUserId();
        // 查询当前文件夹
        List<DocFolderDto> docFolderDtos = findFolders(parentFoldId, companyId);
        // 查询当前文件
        List<DocFileDto> docFileDtos = findFiles(parentFoldId, companyId, companyUserId);
        // 封装数据返回
        return new DocumentDto(docFolderDtos, docFileDtos);
    }
    // 查询文件
    private List<DocFileDto> findFiles(Long parentFoldId, Long companyId, Long companyUserId) {
        // 查询当前文件夹下的文件
        // 1. 查询公共读/公共读写的文件
        LambdaQueryWrapper<DocFile> fileQueryWrapper = new LambdaQueryWrapper<>();
        fileQueryWrapper.eq(DocFile::getCompanyId, companyId);
        fileQueryWrapper.eq(DocFile::getFolderId, parentFoldId);
        fileQueryWrapper.in(DocFile::getPermission, DocumentPermissionEnum.ALL_READ.getPermission(), DocumentPermissionEnum.ALL_READ_WRITE.getPermission());
        fileQueryWrapper.eq(DocFile::getStatus, (short) 1);
        List<DocFile> docFiles1 = docFileMapper.selectList(fileQueryWrapper);
        // 2. 查询私有的文件
        LambdaQueryWrapper<DocFile> fileQueryWrapper2 = new LambdaQueryWrapper<>();
        fileQueryWrapper2.eq(DocFile::getCompanyId, companyId);
        fileQueryWrapper2.eq(DocFile::getFolderId, parentFoldId);
        fileQueryWrapper2.eq(DocFile::getPermission, DocumentPermissionEnum.PRIVATE_READ_WRITE.getPermission());
        fileQueryWrapper2.eq(DocFile::getStatus, (short) 1);
        // 私有的文件必须得是文件的创建者/当前用户
        fileQueryWrapper2.eq(DocFile::getCreateUserId, companyUserId);
        List<DocFile> docFiles2 = docFileMapper.selectList(fileQueryWrapper2);
        // 3. 查询用户为协作者的文件
        List<DocFile> docFiles3 = docFileMapper.findFileByUserIsCollaborator(companyUserId, parentFoldId);
        // 参数汇总
        List<DocFile> docFiles = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(docFiles1)) {
            docFiles.addAll(docFiles1);
        }
        if (CollectionUtil.isNotEmpty(docFiles2)) {
            docFiles.addAll(docFiles2);
        }
        if (CollectionUtil.isNotEmpty(docFiles3)) {
            docFiles.addAll(docFiles3);
        }
        List<DocFileDto> fileDtoList = BeanHelper.copyWithCollection(docFiles, DocFileDto.class);
        // 去重操作
        Set<DocFileDto> docFileSet = new HashSet<DocFileDto>(fileDtoList);
        // 封装创建人名字以及更新人姓名
        List<DocFileDto> docFileDtos = new ArrayList<>();
        for (DocFileDto docFileDto : docFileSet) {
            Long createUserId = docFileDto.getCreateUserId();
            // 根据创建人Id查询创建人详细信息
            SysCompanyUserDTO userDTO = sysUserFeign.findCompanyUserById(createUserId).getData();
            if (userDTO != null) {
                docFileDto.setUserName(userDTO.getUserName());
            }
            // 根据修改人Id查询创建人详细信息
            SysCompanyUserDTO userDto2 = sysUserFeign.findCompanyUserById(docFileDto.getUpdateUserId()).getData();
            if (userDto2 != null) {
                docFileDto.setUpdateUserName(userDto2.getUserName());
            }
            docFileDtos.add(docFileDto);
        }
        return docFileDtos;
    }

    // 查询当前文件夹
    private List<DocFolderDto> findFolders(Long parentFoldId, Long companyId) {
        LambdaQueryWrapper<DocFolder> folderQueryWrapper = new LambdaQueryWrapper<>();
        folderQueryWrapper.eq(DocFolder::getParentId, parentFoldId);
        folderQueryWrapper.eq(DocFolder::getCompanyId, companyId);
        folderQueryWrapper.eq(DocFolder::getStatus, (short) 1);
        List<DocFolder> docFolders = docFolderMapper.selectList(folderQueryWrapper);
        if (CollectionUtil.isEmpty(docFolders)) {
            throw new NCException(ResponseEnum.DATA_NOT_EXISTS);
        }
        List<DocFolderDto> docFolderDtos = BeanHelper.copyWithCollection(docFolders, DocFolderDto.class);
        return docFolderDtos;
    }
    /**
     * 新建文件夹
     */
    @Override
    public void insertFolder(DocFolderDto docFolderDto) {
        Long companyId = CurrentUserHolder.get().getCompanyId();
        Long companyUserId = CurrentUserHolder.get().getCompanyUserId();
        // 校验参数,文件夹名不能不传
        if (StrUtil.isEmpty(docFolderDto.getName()) && docFolderDto.getParentId() == null) {
            throw new NCException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        // 不能有重复文件夹
        LambdaQueryWrapper<DocFolder> folderQueryWrapper = new LambdaQueryWrapper<>();
        folderQueryWrapper.eq(DocFolder::getName, docFolderDto.getName());
        Integer count = docFolderMapper.selectCount(folderQueryWrapper);
        if (count >= 1) {
            throw new NCException(ResponseEnum.valueOf("文件夹名称重复"));
        }
        // 添加文件夹
        DocFolder docFolder = BeanHelper.copyProperties(docFolderDto, DocFolder.class);
        //DocFolder docFolder = new DocFolder();
        //docFolder.setName(name);
        //docFolder.setParentId(parentId);
        docFolder.setCompanyId(companyId);
        docFolder.setCreateTime(new Date());
        docFolder.setStatus((short) 1);
        docFolder.setCreateUserId(companyUserId);
        docFolder.setOrderNum(0);
        docFolderMapper.insert(docFolder);
    }

    /**
     * 根据文档ID查询文档
     *
     * @param id
     * @return
     */
    @Override
    public DocFileDto findDocFileById(Long id) {
        if (id == null) {
            throw new NCException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        DocFile docFile = docFileMapper.selectById(id);
        if (docFile == null) {
            throw new NCException(ResponseEnum.FILE_NOT_FOUND);
        }
        return BeanHelper.copyProperties(docFile, DocFileDto.class);
    }

    /**
     * 分页查询协作者ID以及协作者名字
     * @param
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<DocumentUserDTO> findCollaborationsByPage(Long fileId, Long page, Long pageSize) {

        if (fileId == null) {
            throw new NCException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        Page<DocCollaborations> pages = new Page<>(page,pageSize);
        // 根据文档id查询协作者id
        LambdaQueryWrapper<DocCollaborations> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DocCollaborations::getFileId, fileId);
        pages = docCollaborationsMapper.selectPage(pages, queryWrapper);
        // 分页后的结果
        List<DocCollaborations> pagesRecords = pages.getRecords();
        // 获取协作者id以及数据
        List<DocumentUserDTO> documentUserDTOList = new ArrayList<>();
        if (pagesRecords != null) {
            for (DocCollaborations docCollaborations : pagesRecords) {
                // 根据协作者id查询名称
                SysCompanyUserDTO sysCompanyUserDTO = sysUserFeign.findCompanyUserById(docCollaborations.getCollaborationId()).getData();
                DocumentUserDTO documentUserDTO = new DocumentUserDTO();
                if (sysCompanyUserDTO != null) {
                    documentUserDTO.setId(docCollaborations.getCollaborationId());
                    documentUserDTO.setUserName(sysCompanyUserDTO.getUserName());
                }
                documentUserDTOList.add(documentUserDTO);
            }
        }
        // 封装数据
        return new PageResult<DocumentUserDTO>(pages.getTotal(), pages.getPages(), documentUserDTOList);
    }

    /**
     * 根据文档Id获取所有员工
     * @param docId
     * @return
     */
    @Override
    public List<DocUserCollaborationDTO> findCompanyUsersByDocId(Long docId) {
        // 参数校验
        if (docId == null) {
            throw new NCException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        // 获取所有员工
        List<SysCompanyUserDTO> companyUsers = sysUserFeign.queryAllCompanyUsers().getData();
        // 根据文档id获取文档
        DocFile docFile = docFileMapper.selectById(docId);
        // 获取当前文件的协作者
        LambdaQueryWrapper<DocCollaborations> collaborationsWrapper = new LambdaQueryWrapper<>();
        collaborationsWrapper.eq(DocCollaborations::getFileId, docId);
        List<DocCollaborations> docCollaborations = docCollaborationsMapper.selectList(collaborationsWrapper);
        // 获取所有协作者id集合
        List<Long> coIds = new ArrayList<>();
        for (DocCollaborations docCollaboration : docCollaborations) {
            coIds.add(docCollaboration.getCollaborationId());
        }

        //  记录状态 0既不是拥有者也不是协作者 1是拥有者 2是协作者
        List<DocUserCollaborationDTO> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(companyUsers)) {
            for (SysCompanyUserDTO companyUser : companyUsers) {
                // 记录状态
                Long companyUserId = companyUser.getId();
                int status = docFile.getCreateUserId() == companyUserId ? 1 : coIds.contains(companyUserId) ? 2 : 0;
                DocUserCollaborationDTO docUserCollaborationDTO = new DocUserCollaborationDTO();
                docUserCollaborationDTO.setPhone(companyUser.getMobile());
                docUserCollaborationDTO.setImgUrl(companyUser.getImageUrl());
                docUserCollaborationDTO.setState(status);
                docUserCollaborationDTO.setId(companyUserId);
                docUserCollaborationDTO.setUsername(companyUser.getUserName());
                resultList.add(docUserCollaborationDTO);

                /**
                 *  /*  // 原始 判断--拥有者
                 *    if (docFile.getCreateUserId().equals(companyUser.getId())) {
                 *        DocUserCollaborationDTO docUserCollaborationDTO = new DocUserCollaborationDTO();
                 *        docUserCollaborationDTO.setId(companyUser.getId());
                 *        docUserCollaborationDTO.setUsername(companyUser.getUserName());
                 *        docUserCollaborationDTO.setState(1);
                 *        docUserCollaborationDTO.setImgUrl(companyUser.getImageUrl());
                 *        docUserCollaborationDTO.setPhone(companyUser.getMobile());
                 *        resultList.add(docUserCollaborationDTO);
                 *    }
                 *    // 判断协作者
                 *    if (collaboraionsCount > 0) {
                 *        DocUserCollaborationDTO docUserCollaborationDTO = new DocUserCollaborationDTO();
                 *        docUserCollaborationDTO.setId(companyUser.getId());
                 *        docUserCollaborationDTO.setUsername(companyUser.getUserName());
                 *        docUserCollaborationDTO.setState(2);
                 *        docUserCollaborationDTO.setImgUrl(companyUser.getImageUrl());
                 *        docUserCollaborationDTO.setPhone(companyUser.getMobile());
                 *        resultList.add(docUserCollaborationDTO);
                 *    }
                 *    // 既不是协作者,也不是拥有者
                 *    DocUserCollaborationDTO docUserCollaborationDTO = new DocUserCollaborationDTO();
                 *    docUserCollaborationDTO.setId(companyUser.getId());
                 *    docUserCollaborationDTO.setUsername(companyUser.getUserName());
                 *    docUserCollaborationDTO.setState(0);
                 *    docUserCollaborationDTO.setImgUrl(companyUser.getImageUrl());
                 *    docUserCollaborationDTO.setPhone(companyUser.getMobile());
                 *    resultList.add(docUserCollaborationDTO);*/
            }
            // 返回数据
            return resultList;
        }
        return null;
    }
}
